// src/stores/deptStore.js
import { defineStore } from 'pinia'
import { deptApi } from "@/api/dept/index.js";
import { ElMessage } from "element-plus";

export const useDeptStore = defineStore('dept', {
    state: () => ({
        deptList: [],
        deptDetail: {},
        deptTree: [],
        deptUsers: [],
        pageInfo: {
            pageNum: 1,
            pageSize: 10,
            total: 0,
            totalPage: 0
        },
        userPageInfo: {
            pageNum: 1,
            pageSize: 10,
            total: 0,
            totalPage: 0
        }
    }),
    actions: {
        // 获取部门列表（分页）
        async getDeptList() {
            try {
                const response = await deptApi.getList(this.pageInfo);
                this.deptList = response.data.records;

                this.pageInfo.pageNum = response.data.pageNumber;
                this.pageInfo.pageSize = response.data.pageSize;
                this.pageInfo.total = response.data.totalRow;
                this.pageInfo.totalPage = response.data.totalPage;
            } catch (error) {
                ElMessage.error('获取部门列表失败');
            }
        },

        // 创建新部门
        async createDept(deptData) {
            try {
                const response = await deptApi.create(deptData);
                if (response.code === 200) {
                    ElMessage.success('创建部门成功');
                    await this.getDeptList();
                    return response;
                } else {
                    ElMessage.error(response.message || '创建部门失败');
                    return response;
                }
            } catch (error) {
                ElMessage.error('创建部门失败');
                throw error;
            }
        },

        // 更新部门信息
        async updateDept(deptData) {
            try {
                // 转换字段名以匹配后端 DTO
                const requestData = {
                    deptId: parseInt(deptData.id),
                    name: deptData.name,
                    parentId: parseInt(deptData.parentId),
                    sort: parseInt(deptData.sort),
                    description: deptData.description || ''
                };

                const response = await deptApi.update(requestData);
                if (response.code === 200) {
                    ElMessage.success('更新部门成功');
                    await this.getDeptList();
                    return response;
                } else {
                    ElMessage.error(response.message || '更新部门失败');
                    return response;
                }
            } catch (error) {
                ElMessage.error('更新部门失败');
                throw error;
            }
        },


        // 删除部门（逻辑删除）
        async deleteDept(deptId) {
            try {
                const response = await deptApi.delete(deptId);
                if (response.code === 200) {
                    ElMessage.success('删除部门成功');
                    await this.getDeptList();
                    return response;
                } else {
                    ElMessage.error(response.message || '删除部门失败');
                    return response;
                }
            } catch (error) {
                ElMessage.error('删除部门失败');
                throw error;
            }
        },

        // 获取部门详情
        async getDeptDetail(deptId) {
            try {
                const response = await deptApi.getDetail(deptId);
                if (response.code === 200) {
                    this.deptDetail = response.data;
                    return response.data;
                } else {
                    ElMessage.error(response.message || '获取部门详情失败');
                    return null;
                }
            } catch (error) {
                ElMessage.error('获取部门详情失败');
                throw error;
            }
        },

        // 获取部门树结构
        async getDeptTree() {
          try {
            const response = await deptApi.getTree();
            if (response.code === 200) {
              this.deptTree = response.data;
              return response.data;
            } else {
              ElMessage.error(response.message || '获取部门树失败');
              return [];
            }
          } catch (error) {
            ElMessage.error('获取部门树失败: ' + error.message);
            throw error;
          }
        },

        // 获取部门下的用户列表（分页）
        async getDeptUsers(deptId, pageInfo = {}) {
            try {
                const params = {
                    deptId: deptId,
                    page: pageInfo.pageNum || this.userPageInfo.pageNum,
                    size: pageInfo.pageSize || this.userPageInfo.pageSize
                };

                const response = await deptApi.getUserList(params);
                if (response.code === 200) {
                    this.deptUsers = response.data.records;

                    this.userPageInfo.pageNum = response.data.pageNumber;
                    this.userPageInfo.pageSize = response.data.pageSize;
                    this.userPageInfo.total = response.data.totalRow;
                    this.userPageInfo.totalPage = response.data.totalPage;

                    return response.data;
                } else {
                    ElMessage.error(response.message || '获取部门用户列表失败');
                    return null;
                }
            } catch (error) {
                ElMessage.error('获取部门用户列表失败');
                throw error;
            }
        },

        // 调整部门结构（层级关系和排序）
        async updateDeptStructure(structureData) {
            try {
                const response = await deptApi.updateStructure(structureData);
                if (response.code === 200) {
                    ElMessage.success('调整部门结构成功');
                    // 重新获取部门树
                    await this.getDeptTree();
                    return response;
                } else {
                    ElMessage.error(response.message || '调整部门结构失败');
                    return response;
                }
            } catch (error) {
                ElMessage.error('调整部门结构失败');
                throw error;
            }
        }
    }
})
